package com.lagou.boot;

import com.lagou.handler.UserServiceHandler;
import com.lagou.serializer.JSONSerializer;
import com.lagou.serializer.RpcDecoder;
import com.lagou.serializer.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ServerBoot {

    // 创建一个方法启动服务器
    public static void startServer(String ip,int port) throws InterruptedException {
        // 创建2个线程池对象
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        // 创建服务器启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 设置服务器启动引导类对象
        serverBootstrap.group(boosGroup,workGroup)
                // 设置通道为NIO
                .channel(NioServerSocketChannel.class)
                // 创建监听器
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 获取通道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        // 设置编码
                        pipeline.addLast(new RpcEncoder(Object.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(Object.class, new JSONSerializer()));
//                        pipeline.addFirst(new StringEncoder());
//                        pipeline.addLast(new StringDecoder());
                        // 自定义ChannelHandler对象
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        serverBootstrap.bind(8999).sync();
    }
}
